package com.example.demo.config;

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimplePBEConfig;

/**
 * @Description TODO
 * @Date 2025/4/10 10:56
 * @Author ShaoJie Cen
 */


public class AdvancedJasyptUtil {


    private static final StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();


    public static void init(String secretKey, String algorithm) {
        SimplePBEConfig config = new SimplePBEConfig();
        config.setPassword(secretKey);
        config.setAlgorithm(algorithm);

        // 关键修复点1：设置盐生成器（默认随机盐）
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");

        // 关键修复点2：迭代次数（至少1000次）
        config.setKeyObtentionIterations("1000");

        // 关键修复点3：针对AES算法需设置IV生成器
        if (algorithm.contains("AES")) {
            config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
        }

        encryptor.setConfig(config);
        encryptor.initialize();
    }

    public static String encrypt(String plainText) {
        try {
            return encryptor.encrypt(plainText);
        } catch (Exception e) {
            throw new RuntimeException("加密失败，请检查密钥或算法配置", e);
        }
    }

    public static String decrypt(String encryptedText) {
        try {
            return encryptor.decrypt(encryptedText);
        } catch (Exception e) {
            throw new RuntimeException("解密失败，请检查密钥或密文有效性", e);
        }
    }
}
